package com.sh.interceptor;

import com.aliyun.gts.sso.context.SFLoginAccountContext;
import com.aliyun.gts.sso.domain.LoginAccount;
import com.sh.common.context.AppContextHolder;
import com.sh.common.exception.BizException;
import com.sh.config.Configure;
import com.sh.enums.BizCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        LoginAccount loginAccount = SFLoginAccountContext.getLoginInfo().getLoginAccount();
        if (loginAccount == null) {
            throw new BizException(BizCodeEnum.UNAUTHORIZED);
        }
        Boolean isAdmin = false;
        if (Configure.sysManageAccount.contains(loginAccount.getUserCode())) {
            isAdmin = true;
        }
        AppContextHolder.setUser(loginAccount.getGuid(), loginAccount.getUserCode(), loginAccount.getUserName(), isAdmin);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        AppContextHolder.remove();
    }
}
